import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, DatePicker, Select, Spin, Button } from 'antd';
import { UserOutlined, TeamOutlined, RiseOutlined, TrophyOutlined, ExportOutlined } from '@ant-design/icons';
import { EchartsLine, EchartsColumn, EchartsPie, EchartsArea } from '@/components/Charts';
import { getUserStatistics } from '@/services/userManagementApi';
import { exportStatistics } from '@/services/statisticsApi';
import moment from 'moment';

const { RangePicker } = DatePicker;

const UserStatistics: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [statistics, setStatistics] = useState<any>({});
  const [dateRange, setDateRange] = useState<[moment.Moment, moment.Moment]>([
    moment().subtract(30, 'days'),
    moment(),
  ]);
  const [timeGranularity, setTimeGranularity] = useState<'day' | 'week' | 'month'>('day');

  useEffect(() => {
    loadStatistics();
  }, [dateRange, timeGranularity]);

  const loadStatistics = async () => {
    setLoading(true);
    try {
      const response = await getUserStatistics({
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        granularity: timeGranularity,
      });
      setStatistics(response.data);
    } catch (error) {
      console.error('加载统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 处理导出
  const handleExport = async () => {
    try {
      const blob = await exportStatistics({
        type: 'user',
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        format: 'excel',
      });
      
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `用户统计_${dateRange[0].format('YYYY-MM-DD')}_${dateRange[1].format('YYYY-MM-DD')}.xlsx`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    } catch (error) {
      console.error('导出失败:', error);
    }
  };

  // 用户增长趋势图配置
  const userGrowthConfig = {
    data: statistics.user_growth_trend || [],
    xField: 'date',
    yField: 'count',
    smooth: true,
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '新增用户',
        value: `${datum.count} 人`,
      }),
    },
  };

  // 用户活跃度图配置
  const userActivityConfig = {
    data: statistics.user_activity_trend || [],
    xField: 'date',
    yField: 'active_users',
    smooth: true,
    color: '#52c41a',
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '活跃用户',
        value: `${datum.active_users} 人`,
      }),
    },
  };

  // 用户角色分布图配置
  const roleDistributionConfig = {
    data: statistics.role_distribution || [],
    angleField: 'count',
    colorField: 'role',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'element-active' }],
  };

  // 用户状态分布图配置
  const statusDistributionConfig = {
    data: statistics.status_distribution || [],
    xField: 'status',
    yField: 'count',
    color: ({ status }: any) => {
      const colorMap: Record<string, string> = {
        active: '#52c41a',
        inactive: '#faad14',
        banned: '#ff4d4f',
      };
      return colorMap[status] || '#1890ff';
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: datum.status === 'active' ? '正常' : datum.status === 'inactive' ? '未激活' : '已封禁',
        value: `${datum.count} 人`,
      }),
    },
  };

  return (
    <PageContainer
      header={{
        title: '用户统计',
        extra: [
          <Button key="export" icon={<ExportOutlined />} onClick={handleExport}>
            导出数据
          </Button>,
        ],
      }}
    >
      <Spin spinning={loading}>
        {/* 筛选条件 */}
        <Card style={{ marginBottom: 24 }}>
          <Row gutter={16} align="middle">
            <Col>
              <span>时间范围：</span>
              <RangePicker
                value={dateRange}
                onChange={(dates) => dates && setDateRange(dates)}
                style={{ marginLeft: 8 }}
              />
            </Col>
            <Col>
              <span style={{ marginLeft: 16 }}>时间粒度：</span>
              <Select
                value={timeGranularity}
                onChange={setTimeGranularity}
                style={{ width: 100, marginLeft: 8 }}
              >
                <Select.Option value="day">按天</Select.Option>
                <Select.Option value="week">按周</Select.Option>
                <Select.Option value="month">按月</Select.Option>
              </Select>
            </Col>
          </Row>
        </Card>

        {/* 统计卡片 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总用户数"
                value={statistics.total_users || 0}
                prefix={<UserOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="活跃用户数"
                value={statistics.active_users || 0}
                prefix={<TeamOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="新增用户数"
                value={statistics.new_users || 0}
                prefix={<RiseOutlined />}
                valueStyle={{ color: '#faad14' }}
                suffix={`(${statistics.growth_rate || 0}%)`}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="平均学习时长"
                value={statistics.avg_study_time || 0}
                prefix={<TrophyOutlined />}
                valueStyle={{ color: '#722ed1' }}
                suffix="小时"
              />
            </Card>
          </Col>
        </Row>

        {/* 图表区域 */}
        <Row gutter={16}>
          <Col span={12}>
            <Card title="用户增长趋势" style={{ marginBottom: 16 }}>
              <EchartsLine {...userGrowthConfig} height={300} />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="用户活跃度趋势" style={{ marginBottom: 16 }}>
              <EchartsArea {...userActivityConfig} height={300} />
            </Card>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Card title="用户角色分布">
              <EchartsPie {...roleDistributionConfig} height={300} />
            </Card>
          </Col>
          <Col span={12}>
            <Card title="用户状态分布">
              <EchartsColumn {...statusDistributionConfig} height={300} />
            </Card>
          </Col>
        </Row>

        {/* 详细数据表格 */}
        <Card title="地区分布" style={{ marginTop: 16 }}>
          <Row gutter={16}>
            {(statistics.region_distribution || []).map((region: any, index: number) => (
              <Col span={6} key={index} style={{ marginBottom: 16 }}>
                <Card size="small">
                  <Statistic
                    title={region.region}
                    value={region.count}
                    suffix="人"
                    valueStyle={{ fontSize: '18px' }}
                  />
                  <div style={{ marginTop: 8, fontSize: '12px', color: '#666' }}>
                    占比: {region.percentage}%
                  </div>
                </Card>
              </Col>
            ))}
          </Row>
        </Card>

        {/* 学习行为统计 */}
        <Card title="学习行为统计" style={{ marginTop: 16 }}>
          <Row gutter={16}>
            <Col span={8}>
              <Statistic
                title="平均练习次数"
                value={statistics.avg_practice_count || 0}
                suffix="次"
              />
            </Col>
            <Col span={8}>
              <Statistic
                title="平均完成课程数"
                value={statistics.avg_completed_courses || 0}
                suffix="门"
              />
            </Col>
            <Col span={8}>
              <Statistic
                title="平均获得成就数"
                value={statistics.avg_achievements || 0}
                suffix="个"
              />
            </Col>
          </Row>
        </Card>
      </Spin>
    </PageContainer>
  );
};

export default UserStatistics;
